﻿using System.IO;

namespace WP7.Extensions.Helpers
{
    public class StreamHelper
    {
        /// <summary>
        /// Copies a stream and writes it
        /// </summary>
        /// <param name="readStream">The stream to be read</param>
        /// <param name="writeStream">The stream to be written</param>
        /// <param name="closeOnFinalize"></param>
        /// <returns>Total number of written bytes</returns>
        public static long CopyStream(Stream readStream, Stream writeStream, bool closeOnFinalize)
        {
            long totalBytes = 0;
            const int size = 4096;
            byte[] bytes = new byte[size];

            try
            {
                int numBytes;
                while ((numBytes = readStream.Read(bytes, 0, size)) > 0)
                {
                    totalBytes += numBytes;
                    writeStream.Write(bytes, 0, numBytes);
                }
            }
            finally
            {
                if (writeStream != null && closeOnFinalize)
                {
                    writeStream.Close();
                    writeStream.Dispose();
                }

                if (readStream != null && closeOnFinalize)
                {
                    readStream.Close();
                    readStream.Dispose();
                }
            }

            return totalBytes;
        }
    }
}
